/**
 * MailService.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2013年8月27日
 */
package com.pshare.msg.email.service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.annotation.PostConstruct;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;

import com.pshare.framework.listener.MsgListener;

/**
 * 邮件业务层
 */
@Service
public class MailService implements MsgListener {

	private static final Logger logger = Logger.getLogger(MailService.class);

	private String usertemplate;
	private String systemplate;
	private JavaMailSender mailSender;
	private VelocityConfigurer configurer;
	private VelocityEngine velocityEngine;

	private ExecutorService exec = Executors.newCachedThreadPool();

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setConfigurer(VelocityConfigurer configurer) {
		this.configurer = configurer;
	}

	public void setUsertemplate(String usertemplate) {
		this.usertemplate = usertemplate;
	}

	public void setSystemplate(String systemplate) {
		this.systemplate = systemplate;
	}

	@PostConstruct
	public void init() {
		//velocityEngine = configurer.getVelocityEngine();
	}
	
	public boolean sendMail(String subject, String content, List<File> attachment, String[] tos, String[] ccs,
			String[] bccs) {
		return sendMail(subject, content, attachment, tos, ccs, bccs);
	}

	/**
	 * 发送邮件
	 * 
	 * @param subject 标题
	 * @param content 内容
	 * @param attachment 附件
	 * @param tos 收件人
	 * @param ccs 抄送
	 * @param bccs 暗送
	 * @param toSys 是否发送给系统管理员
	 * @return boolean 是否发送成功
	 */
	public boolean sendMail(String subject, String content, List<File> attachment, String[] tos, String[] ccs,
			String[] bccs, boolean toSys) {

		MailJob job = new MailJob(subject, content, attachment, toSys);
		job.setTos(tos);
		job.setCcs(bccs);
		job.setBccs(bccs);
		Future<String> future = exec.submit(job);

		String result = "";
		try {
			result = future.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return result.equals("1");
	}

	class MailJob implements Callable<String> {
		private String subject;
		private String content;
		private String[] tos;
		private String[] ccs;
		private String[] bccs;
		private List<File> attachment;
		private boolean toSys;

		public MailJob(String subject, String content, List<File> attachment, boolean toSys) {
			this.subject = subject;
			this.content = content;
			this.attachment = attachment;
			this.toSys = toSys;
		}

		public void setTos(String[] tos) {
			this.tos = tos;
		}

		public void setCcs(String[] ccs) {
			this.ccs = ccs;
		}

		public void setBccs(String[] bccs) {
			this.bccs = bccs;
		}

		@Override
		public String call() throws Exception {
			try {
				MimeMessage mailMessage = mailSender.createMimeMessage();
				MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

				// 添加附件
				if (attachment != null) {
					for (File file : attachment) {
						messageHelper.addAttachment(file.getName(), file);
					}
				}
				messageHelper.setTo(tos);// 接受者
				if (ccs != null && ccs.length > 0) {
					messageHelper.setCc(ccs);
				}
				if (bccs != null && bccs.length > 0) {
					messageHelper.setBcc(bccs);
				}
				messageHelper.setFrom(((JavaMailSenderImpl) mailSender).getUsername());
				messageHelper.setSubject(subject);
				messageHelper.setText(renderMail(content, toSys), true);
				mailSender.send(mailMessage);

				logger.info("邮件发送成功。接收人：" + tos + ". 标题：" + subject);
			} catch (Exception e) {
				logger.error("邮件发送失败。接收人：" + tos + ". 标题：" + subject);
				logger.error(e.getMessage(), e);
				return "0";
			}

			return "1";
		}
	}

	private String renderMail(String content, boolean toSys) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("content", content);
		String template = toSys ? systemplate : usertemplate;
		return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, "UTF-8", model);
	}

	@Override
	public void sendMsg(String title, String content, String[] receivers, Boolean toSys) {
		if (receivers == null || receivers.length == 0) {
			logger.error("no receiver set");
			return;
		}

		sendMail(title, content, null, receivers, null, null, toSys);
	}

}
